package com.qiguliuxing.dts.job.task;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.google.common.collect.Maps;
import com.qiguliuxing.dts.common.constant.CommConsts;
import com.qiguliuxing.dts.common.type.BrokerageTypeEnum;
import com.qiguliuxing.dts.common.util.DateTimeUtils;
import com.qiguliuxing.dts.service.base.DtsAccountService;
import com.qiguliuxing.dts.service.system.SystemConfig;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * 代理结算job
 * @author qiguliuxing
 * @since 1.0.0
 */
@Component
public class AgentSettlementJob implements SimpleJob {
    private static final Logger logger = getLogger(AgentSettlementJob.class);

    @Autowired
    private DtsAccountService accountService;

    /**
     * 执行作业.
     *  自动结算代理佣金
     * <p>
     * 每月8-20号 凌晨1点半执行，自动计算代理用户的佣金到对应账户，作为系统结算。
     * <p>
     * 注意，仅统计上个月订单状态为已经完成，即订单状态为 401 402 的订单。
     * @param shardingContext 分片上下文
     */
    @Override
    public void execute(ShardingContext shardingContext) {
        logger.info(String.format("Thread ID: %s, 作业分片总数: %s,当前分片项: %s.当前参数: %s,作业名称: %s.作业自定义参数: %s",
                Thread.currentThread().getId(),
                shardingContext.getShardingTotalCount(),
                shardingContext.getShardingItem(),
                shardingContext.getShardingParameter(),
                shardingContext.getJobName(),
                shardingContext.getJobParameter()
        ));

        Map<String, Object> paramsMap = Maps.newHashMapWithExpectedSize(CommConsts.INIT_HASH_MAP_SIZE);
        paramsMap.put("shardingTotalCount", shardingContext.getShardingTotalCount());
        paramsMap.put("shardingItem", shardingContext.getShardingItem());

        List<Integer> sharedUserIds = accountService.findAllSharedUserId(paramsMap);
        logger.info("自动结算代理佣金定时任务,共找到  " + sharedUserIds.size() + " 位代理用户,开始统计佣金...");

        for (Integer sharedUserId : sharedUserIds) {
            try {
                accountService.setSettleMentAccount(sharedUserId, DateTimeUtils.getPrevMonthEndDay(), BrokerageTypeEnum.SYS_APPLY.getType().intValue(), SystemConfig.frequentAgencyModel());
            } catch (Exception e) {
                logger.error("自动结算出错:" + e.getMessage());
                e.printStackTrace();
            }
        }

    }
}
